package com.xiaowei.aidemo1.utils;

import com.baidu.aip.imageclassify.AipImageClassify;
import com.baidu.aip.nlp.AipNlp;
import com.baidu.aip.ocr.AipOcr;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;

public class AiUtils {
    //设置APPID/AK/SK
    public static final String APP_ID = "*******";
    public static final String API_KEY = "*******";
    public static final String SECRET_KEY = "*******";

    public static final String APP_ID_IMG = "*******";
    public static final String API_KEY_IMG = "*******";
    public static final String SECRET_KEY_IMG = "*******";

    public static final String APP_ID_NLP = "*******";
    public static final String API_KEY_NLP  = "*******";
    public static final String SECRET_KEY_NLP  = "*******";

    public static String picToWords(MultipartFile file) throws IOException {
        // 初始化一个AipOcr
        AipOcr client = new AipOcr(APP_ID, API_KEY, SECRET_KEY);
        // 调用接口
        JSONObject res = client.basicGeneral(file.getBytes(), new HashMap<String, String>());
        JSONArray words_result = res.getJSONArray("words_result");
        String result = "";
        for (int i = 0; i < words_result.length(); i++) {
            JSONObject jsonObject = words_result.getJSONObject(i);
            Object words = jsonObject.get("words");
            String s = (String) words;
            result += s + "";
        }
        return result;
    }

    public static String imgRecognition(MultipartFile file) throws IOException {

        // 初始化一个AipImageClassify
        AipImageClassify client = new AipImageClassify(APP_ID_IMG, API_KEY_IMG, SECRET_KEY_IMG);

        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 可选：设置代理服务器地址, http和socket二选一，或者均不设置
//        client.setHttpProxy("proxy_host", proxy_port);  // 设置http代理
//        client.setSocketProxy("proxy_host", proxy_port);  // 设置socket代理

        // 调用接口
        //图片的绝对地址
        JSONObject res = client.advancedGeneral(file.getBytes(), new HashMap<String, String>());
        return res.toString(2);
    }


    public static String correction(String text) {
        // 初始化一个AipNlp
        AipNlp client = new AipNlp(APP_ID, API_KEY, SECRET_KEY);
        // 传入可选参数调用接口
        HashMap<String, Object> options11 = new HashMap<String, Object>();

        // 文本纠错
        JSONObject res11 = client.ecnet(text, options11);
        return res11.toString(2);
    }
}
